<?php

namespace App\Livewire\Auth;

use App\Models\Share;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Validate;
use Livewire\Component;

class Register extends Component
{
    #[Validate('required')]
    public string $account = '';

    #[Validate('required|string|min:6|confirmed')]
    public string $password = '';

    #[Validate('required')]
    public string $password_confirmation = '';

    #[Validate('nullable|string|max:50|exists:shares,code')]
    public ?string $share_code;

    public function mount()
    {
        $this->share_code = request('share_code', '');
    }

    public function render()
    {
        return view('livewire.auth.register');
    }

    public function submit(Request $request)
    {
        $data = $this->validate();

        $arr = [
            ...$data,
            ...['ip' => $request->ip()],
        ];

        if ($this->share_code) {
            $arr['others']['parent_id'] = Share::where('code', $this->share_code)->value('user_id');
        }

        $user = User::query()->create($arr);

        event(new Registered($user));

        Auth::login($user);

        return to_route('home');
    }
}
